package ibps.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * Created by lujianing on 2017/5/7.
 */
@Data
@AllArgsConstructor
public class PdfUtil {
	private File targetFile;
	private String picPath;

	public void createPdf(String content) throws IOException, DocumentException, com.lowagie.text.DocumentException {
		ITextRenderer render = new ITextRenderer();
		ITextFontResolver fontResolver = render.getFontResolver();
		String font = "simhei.ttf";
		fontResolver.addFont(font, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		// 解析html生成pdf
		render.setDocumentFromString(content);
		// 解决图片相对路径的问题
		render.getSharedContext().setBaseURL(picPath);

		render.layout();
		render.createPDF(new FileOutputStream(targetFile));
	}
	
	public static void main(String[] args) throws IOException, DocumentException, com.lowagie.text.DocumentException {
		Map<String, Object> params = new HashMap<>();
		params.put("name", "鲁家宁");
		String fkTemplatePath = "template_qj.html";
		String content = new FkUtil(params, fkTemplatePath).render();
		String picPath = "file:/" + PathUtil.getCurrentPath() + "/logo.png";
		
		new PdfUtil(new File("target/qj.pdf"),picPath).createPdf(content);
	}
}
